clear

set seed 23423

local colist HU   SE   RO PT PL NO  IT  GB FR  ES DK DE CZ BG    AT
local numberco : word count `colist'
local firstco: word 1 of `colist'


foreach nuts in 2 3{


foreach ltfpvar in w1_lvapw w1_log_TFPr_tfas{

* loop
local i=1
local loopnum 1000

while(`i'<=`loopnum'){


di "Loop `i'"

foreach co in  `colist'{

quietly use "$BvD_input/Amadeus_Europe_2010_2019_coded_latest_NUTS`nuts'_`co'.dta", clear

quietly cap rename `ltfpvar' lA

	quietly gen order=_n

	*Groups	
	quietly egen JT		=group(J T)
	quietly egen ST		=group(S T)
	quietly egen SJT	=group(S J T)
	quietly egen tag_SJT=tag(SJT)
	quietly egen tag_ST	=tag(ST)
	
	*tau weights
	quietly bys SJT: egen emp_SJT	=total(empl)
	quietly bys ST: egen emp_ST		=total(empl)
	quietly bys JT: egen emp_JT		=total(empl)

	* share of industry in total local employment
	quietly gen empshare_SJT		=emp_SJT/emp_ST
	
run "$BvD_code/Cov_worker.do"

		foreach svar in xi tau {
			tempvar weight
			if("`svar'"=="tau"){
				local tag SJTR
				gen `weight'=empshare_SJT
				}
			else{
				local tag STR
				gen `weight'=1
				}
		quietly cor `svar'_Rb0 `svar'_Rb1   [aw=`weight'] if tag_`tag', cov
		quietly local cov_`svar'b=`r(cov_12)'
		quietly local var_`svar'=`r(Var_2)'
		}
		
		quietly clear
		quietly set obs 1
		foreach svar in xi tau{
		quietly gen cov_`svar'b=`cov_`svar'b'
		quietly gen varhalf_`svar'=`var_`svar''
		quietly gen coef_`svar'=`cov_`svar'b'/varhalf_`svar'
		}
		quietly gen co="`co'"

		if("`co'"=="`firstco'"){
			quietly save "$BvD_input/BvD_results_loop_temp`nuts'.dta", replace
			}
		else{
			quietly append using "$BvD_input/BvD_results_loop_temp`nuts'.dta"
			quietly save "$BvD_input/BvD_results_loop_temp`nuts'.dta", replace
			}
		}
	
 use "$BvD_input/BvD_results_loop_temp`nuts'.dta", replace


gen tfpvar="`ltfpvar'"
quietly gen iteration=`i'

if ("`i'"=="1" & "`ltfpvar'"=="w1_lvapw"){
	quietly save "$BvD_output/BvD_results_loop`nuts'.dta", replace
	}
	else{
	quietly append using "$BvD_output/BvD_results_loop`nuts'.dta"
	quietly save "$BvD_output/BvD_results_loop`nuts'.dta", replace
	}
 
local i=`i'+1
}
}
gen neg_xi=1 if cov_xi<=0
gen neg_tau=1 if cov_tau<=0
bys co tfpvar: egen plteq0_xi=total(neg_xi)
bys co  tfpvar: egen plteq0_tau=total(neg_tau)
collapse (first) plteq0* (mean) mean_cov_xi=cov_xi mean_cov_tau=cov_tau (sd) sd_cov_xi=cov_xi sd_cov_tau=cov_tau (median) med_cov_xi=cov_xi med_cov_tau=cov_tau, by(co tfpvar)
	 save "$BvD_output/BvD_results_cov`nuts'.dta", replace

}
